import React from 'react';
import ReactDOM from 'react-dom';
import './css/todoMvc.css'

import { Header, TodoList, Footer } from './todoMvc';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      items: JSON.parse(localStorage.getItem('ReactTodoMvc')) || [],
      header:{
        oddChange: this.oddChange.bind(this),
        removeTodo: this.removeTodo.bind(this),
        status:'All',
        editTodo : this.editTodo.bind(this)
      },

      footer:{
        handlerStatus:this.handlerStatus.bind(this),
        removeComplete:this.removeComplete.bind(this)
      }
    }
  }


  render() {
    return ( 
      <React.Fragment>
        <div className ='todos'>
          <Header items={this.state.items} addTodo={this.addTodo.bind(this)} handlerCheckAll={this.handlerCheckAll.bind(this)}></Header> 
          <TodoList items={this.state.items} handler={this.state.header}></TodoList> 
          <Footer items={this.state.items} handler={this.state.footer}></Footer>
        </div> 
      </React.Fragment>
    )
  }

  // 添加一条todo
  addTodo(todo) {
    this.setState({
      items:this.state.items.concat(todo)
    }, function () {
      // localStorage.setItem('ReactTodoMvc', JSON.stringify(this.state.items))
      this.storageItems()
    })
  }

  storageItems() {
    localStorage.setItem('ReactTodoMvc', JSON.stringify(this.state.items))
  }

  // 全选功能 就是接受header组件全选状态 然后把它的状态赋值给 数组的isDone
  handlerCheckAll(check) {
    this.state.items.forEach(item => item.isDone = check);
    this.setState({
      items:this.state.items
    }, function () {
      this.storageItems()
    })
  }

  // 单选框发生变化的时候更改数组的isDone
  oddChange(todo,isDone) {
    const index = this.state.items.findIndex(item => item.id === todo.id)
    this.setState({
      items : this.state.items.map((item,idx) => idx === index ? {...item,isDone:isDone} : item)
    }, function () {
      this.storageItems()
    })
  }
  // 删除一条todo
  removeTodo(id) {
    const index = this.state.items.findIndex(item => item.id === id)
    this.state.items.splice(index, 1);
    this.setState({
      items:this.state.items
    }, function () {
      this.storageItems()
    })
  }

  // 根据状态来渲染list
  handlerStatus(status) {
    console.log(status)
    this.setState({
      header:{
        status:status
      }
    })
  }
  // edittodo
  editTodo(id,title) {
    const index = this.state.items.findIndex(item => item.id === id);
    this.setState({
      items:this.state.items.map((item, idx) => idx === index ? {...item, title:title} : item)
    }, function () {
      this.storageItems()
    })
  }

  // 清除所有已完成
  removeComplete() {
    this.state.items.filter(item => !item.isDone);
    this.setState({
      items : this.state.items.filter(item => !item.isDone)
    }, function () {
      this.storageItems()
    })
  }
}

ReactDOM.render( 
  <App></App>,

  document.getElementById('root')
)